#include "main.h"

#include <readline/readline.h>
#include <readline/history.h>


/* avoiding error 'Undefined symbol "nspr_use_zone_allocator"' when dlopen */
PRBool nspr_use_zone_allocator = PR_FALSE;

void console_set_lock(unsigned char is_locked) {
	static PRLock *lock = NULL;
	if (!lock)
		lock = PR_NewLock();
	if (is_locked)
		PR_Lock(lock);
	else
		PR_Unlock(lock);
}


/**
 *
 */
int main(int argc, char **argv) {
	trace1("main");
	char *line, *prev_line;
	jsval rval;	
	int ret = 0;
	int i;
		
	unsigned int iseed = (unsigned int)time(NULL);
	srand (iseed);

	JSContext *cx = js_init();
	
	init_console();
	init_threadpool();

	if (argc >= 2) {
		int n = 0;
		jsval *list = (jsval *)malloc(sizeof(jsval *) * (argc - 1));
		list[n++] = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, argv[0]));
		for (i = 2; i < argc; ++i)
			list[n++] = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, argv[i]));
		JSObject *ar = JS_NewArrayObject(cx, argc - 1, list);
		JS_DefineProperty(cx, JS_GetGlobalObject(cx), "arguments",
			OBJECT_TO_JSVAL(ar),
			JS_PropertyStub,

#if JS_VERSION > 180
    JS_StrictPropertyStub,
#else
    JS_PropertyStub,
#endif
			
			JSPROP_READONLY | JSPROP_ENUMERATE | JSPROP_PERMANENT
		);
		if (!eval_file(cx, argv[1], 0, &rval))
			ret = 1;
		check_exception(cx);
		goto main_end;
	}

	if (!is_interactive()) {
		if (!eval_stream(cx, stdin, "<stdin>", 0, &rval))
			ret = 1;
		goto main_end;
	}

	
#define BUF_SIZE 10000	

	prev_line = (char *)malloc(1000*sizeof(char));	
	jsrefcount rc;
	char *buf = (char *)malloc(BUF_SIZE);
	
	printf("%s\n\n", WELCOME_TEXT);			

	char histfilename[1000];
	sprintf(histfilename, "%s/.jsrun_history", getenv("HOME"));
	FILE *histfile = fopen(histfilename, "a");
	fclose(histfile);

	
	if (0 != read_history(histfilename))
		fatal("read_history()");

	while (1) {
		rc = JS_SuspendRequest(cx);
		line = readline(PS1);		
		JS_ResumeRequest(cx, rc);
		if (!line) break;		
		if (0 == strcmp(line, "q")) break;
		if (0 == strcmp(line, "quit")) break;					
		if (!*line) continue;
		if (prev_line && (strcmp(line, prev_line) != 0)) {
			add_history(line);

			if (0 != append_history(1, histfilename))
				fatal("append_history()");
			
			if (strlen(line) < 1000)
				strcpy(prev_line, line);
		}
		js_preprocess_string(buf, BUF_SIZE, line);	
		if (eval(cx, buf, "<stdin>", 1, 0, &rval))
			if (!JSVAL_IS_VOID(rval))
				printf("%s\n", vtoa(cx, rval));
		check_exception(cx);
	}
	free(prev_line);	
	
main_end:
	JS_DestroyContext(cx);
	
	return ret;
}



